var ws;
var game={
    room:0,
    room_number:globalData.roomNumber,
    room_url:0,
    score:0,
    status:0,
    time:-1,
    round:0,
    total_num:12,
    currentScore:0,
    cardDeal:0,
    can_open:0,
    can_look:1,
    is_play:!1,
    creator_id:0,
};
var message=[
    {num:0,text:"玩游戏，请先进群"},
    {num:1,text:"群内游戏，切勿转发"},
    {num:2,text:"别磨蹭，快点打牌"},
    {num:3,text:"我出去叫人"},
    {num:4,text:"你的牌好靓哇"},
    {num:5,text:"我当年横扫澳门五条街"},
    {num:6,text:"算你牛逼"},
    {num:7,text:"别吹牛逼，有本事干到底"},
    {num:8,text:"输得裤衩都没了"},
    {num:9,text:"我给你们送温暖了"},
    {num:10,text:"谢谢老板"}
    ];
var wsOperation={
    JoinRoom:"JoinRoom",
    ReadyStart:"ReadyStart",
    CloseRoom:"CloseRoom",
    PrepareJoinRoom:"PrepareJoinRoom",
    AllGamerInfo:"AllGamerInfo",
    UpdateGamerInfo:"UpdateGamerInfo",
    UpdateAccountStatus:"UpdateAccountStatus",
    StartLimitTime:"StartLimitTime",
    CancelStartLimitTime:"CancelStartLimitTime",
    GameStart:"GameStart",
    NotyChooseChip:"NotyChooseChip",
    CardInfo:"CardInfo",
    PkCard:"PkCard",
    UpdateAccountScore:"UpdateAccountScore",
    OpenCard:"OpenCard",
    Win:"Win",
    Discard:"Discard",
    BroadcastVoice:"BroadcastVoice",
    ClickToLook:"ClickToLook",
    ChooseChip:"ChooseChip",
    GrabBanker:"GrabBanker",
    PlayerMultiples:"PlayerMultiples",
    ShowCard:"ShowCard",
    UpdateAccountShow:"UpdateAccountShow",
    UpdateAccountMultiples:"UpdateAccountMultiples",
    StartBet:"StartBet",
    StartShow:"StartShow",
    RefreshRoom:"PullRoomInfo",
    //明牌
    MyCards: "MyCards",
    //观战功能
    GuestRoom:"GuestRoom",
    AllGuestInfo:"AllGuestInfo",
    UpdateGuestInfo:"UpdateGuestInfo"
};
    
var httpModule={
    getManageInfo: function() {
        var postData = { "account_id": userData.accountId, "room_number":globalData.roomNumber,"game_type":24 };
        Vue.http.post(globalData.baseUrl + 'f/getManageInfo', postData).then(function(response) {
            logMessage(response.body);
            var bodyData = response.body;

            if (bodyData.result == 0) {
                if (bodyData.data.length == 0) {
                    if (appData.roomCard <= 0) {
                        reconnectSocket();
                        appData.is_connect = true;
                    } else {
                        reconnectSocket();
                        appData.is_connect = true;
                    }
                } else {
                    appData.activity = bodyData.data.concat();
                    viewMethods.clickShowAlert(5, appData.activity[0].content);
                }
            } else {
                //logMessage(bodyData.result_message);
                viewMethods.clickShowAlert(8,bodyData.result_message);
            }

        }, function(response) {
            logMessage(response.body);
        });
    },
};
var socketModule={
    //观战功能
    processGuestRoom:function(e){
        appData.game.room=e.data.room_id;
        appData.game.round=Math.ceil(e.data.game_num);
        appData.game.total_num=Math.ceil(e.data.total_num);
        appData.game.score=Math.ceil(e.data.pool_score);
        appData.game.status=Math.ceil(e.data.room_status);
        appData.game.creator_id = Math.ceil(e.data.creator_id);
        appData.game.currentScore = Math.ceil(e.data.benchmark);

        if(2==appData.game.status){
            appData.game.cardDeal=3;
        }
        
        appData.scoreboard=e.data.scoreboard;
        viewMethods.clickCloseAlert();
        appData.showGuest=0;
    },
    processAllGuestInfo:function(e){
        appData.guests=[];
        if(e.data){
            for(var t=0;t<e.data.length;t++){
                appData.guests.push({
                    account_id:e.data[t].account_id,
                    avatar:e.data[t].headimgurl,
                    nickname:e.data[t].nickname
                });
                for(var a=0;a<appData.player.length;a++)
                    if(appData.player[a].account_id==e.data[t].account_id){
                        appData.player[a].is_guest=1;
                        if(appData.player[a].account_status<1){
                            appData.player[a].account_id=0;
                        }
                    }
            }
        }
        appData.isWatching=0;
        for(var i=0;i<appData.guests.length;i++)
            if(appData.guests[i].account_id==userData.accountId){
                appData.isWatching=1;
            }
        console.log(appData.player);
    },
    processUpdateGuestInfo:function(e){
        for(a=0;a<appData.guests.length;a++)
            if(appData.guests[a].account_id==e.data.account_id){
                break;
            }
        if(e.data.is_guest == 1){
            if(a == appData.guests.length){
                appData.guests.push({
                    account_id:e.data.account_id,
                    avatar:e.data.headimgurl,
                    nickname:e.data.nickname
                });
            }
            for(var n=0;n<appData.player.length;n++)
                if(appData.player[n].account_id==e.data.account_id){
                    appData.player[n].is_guest=1;
                    if(appData.player[n].account_status<1){
                        appData.player[n].account_id=0;

                        appData.showSitdownButton = appData.isWatching;
                    }
                }
        } else {
            appData.guests.splice(a,1);
        }
    },

    closeSocket:function(){
        if(ws)try{ws.close()}catch(e){console.log(e)}
    },
    sendData:function(e){
        try{if(console.log("websocket state："+ws.readyState),ws.readyState==WebSocket.CLOSED)return void reconnectSocket();
        ws.readyState==WebSocket.OPEN?ws.send(JSON.stringify(e)):
        ws.readyState==WebSocket.CONNECTING?setTimeout(function(){socketModule.sendData(e)},1e3):(console.log("websocket state："+ws.readyState),
            errorSocket(e.operation,JSON.stringify(e)))}catch(e){console.log(e)}
    },
    sendPrepareJoinRoom:function(){
        socketModule.sendData({operation:wsOperation.PrepareJoinRoom,account_id:userData.accountId,session:globalData.session,
            data:{room_number:globalData.roomNumber}})
    },
    sendJoinRoom:function(){
        socketModule.sendData({
            operation:wsOperation.JoinRoom,
            account_id:userData.accountId,
            session:globalData.session,
            data:{
                room_number:globalData.roomNumber
            }
        });
    },
    //观战功能
    sendGuestRoom: function() {
        socketModule.sendData({
            operation: wsOperation.GuestRoom,
            account_id: userData.accountId,
            session: globalData.session,
            data: {
                room_number: globalData.roomNumber
            }
        });
    },
    sendRefreshRoom:function(){
        socketModule.sendData({
            operation:wsOperation.RefreshRoom,
            account_id:userData.accountId,
            session:globalData.session,
            data:{room_id:appData.game.room
            }
        });
    },
    sendReadyStart:function(){
        socketModule.sendData({
            operation:wsOperation.ReadyStart,
            account_id:userData.accountId,
            session:globalData.session,
            data:{
                room_id:appData.game.room
            }
        });
    },
    sendCloseRoom:function(){
        socketModule.sendData({
            operation: wsOperation.CloseRoom,
            account_id: userData.accountId,
            session: globalData.session,
            data: {
                room_number: globalData.roomNumber
            }
        });
    },
    sendBroadcastVoice:function(e){
        socketModule.sendData({
            operation:wsOperation.BroadcastVoice,
            account_id:userData.accountId,
            session:globalData.session,
            data:{
                room_id:appData.game.room,
                voice_num:e
            }
        });
    },
   
    sendClickToLook:function(){
        socketModule.sendData({
            operation:wsOperation.ClickToLook,
            account_id:userData.accountId,
            session:globalData.session,
            data:{
                room_id:appData.game.room
            }
        });
    },
    sendChooseChip:function(e){
        socketModule.sendData({
            operation:wsOperation.ChooseChip,
            account_id:userData.accountId,
            session:globalData.session,
            data:{
                room_id:appData.game.room,
                score:e
            }
        });
    },
    sendDiscard:function(){
        socketModule.sendData({
            operation:wsOperation.Discard,
            account_id:userData.accountId,
            session:globalData.session,
            data:{
                room_id:appData.game.room
            }
        })
    },
    sendOpenCard:function(){
        socketModule.sendData({
            operation:wsOperation.OpenCard,
            account_id:userData.accountId,
            session:globalData.session,
            data:{room_id:appData.game.room
            }
        });
    },
    sendPkCard:function(e){
        socketModule.sendData({
            operation:wsOperation.PkCard,
            account_id:userData.accountId,
            session:globalData.session,
            data:{
                room_id:appData.game.room,
                other_account_id:e
            }
        });
    },
    processGameRule: function(obj) {
        if (obj.data.chip_type) {

            appData.ruleInfo.chip_type = obj.data.chip_type;
            appData.ruleInfo.disable_pk = obj.data.disable_pk;
            appData.ruleInfo.disable_look = obj.data.disable_look;
            appData.ruleInfo.ticket_count = obj.data.ticket_count;
            appData.ruleInfo.upper_limit = obj.data.upper_limit;
            appData.ruleInfo.default_score = obj.data.default_score;
            appData.ruleInfo.pk_score = obj.data.pk_score;
            appData.ruleInfo.look_score = obj.data.look_score;
            appData.ruleInfo.play_mode = obj.data.play_mode;
            appData.ruleInfo.xipai_score = obj.data.xipai_score;
            appData.game.creator_id = obj.data.creator_id;
            if (appData.ruleInfo.disable_look == 1 && appData.ruleInfo.disable_pk == 1) {
                appData.ruleInfo.rule_height = 60;
            } else {
                appData.ruleInfo.rule_height = 30;
            }
            if(2==appData.ruleInfo.chip_type){
                appData.scoreList1=[10,20,25,50];
                appData.scoreList2=[4,8,10,20];
            } else if (1==appData.ruleInfo.chip_type) {
                appData.scoreList1=[5,10,20,25];
                appData.scoreList2=[2,4,8,10];
            }else {
                appData.scoreList1=[15,25,50,100];
                appData.scoreList2=[ 6,10,20,40];
            }
        }
    },
    processPrepareJoinRoom:function(obj){
        if(4==obj.data.room_status){
            appData.roomStatus=obj.data.room_status;
            viewMethods.clickShowAlert(8,obj.result_message);
            return;
        }
        
        this.processGameRule(obj);  //复用规则

        wxModule.config();

        // if(0==e.data.user_count){
        //     socketModule.sendJoinRoom();
        // } else if(""!=e.data.alert_text){
        //     viewMethods.clickShowAlert(4,e.data.alert_text);
        // } else {
        //     socketModule.sendJoinRoom();
        // }
        //观战功能
        if(obj.data.is_member){
            socketModule.sendJoinRoom();
        } else {
            if(obj.data.can_join){
                if(obj.data.can_guest){
                    appData.joinType=1;
                    if(obj.data.room_users.length >= 1){
                        obj.data.alert_text = "房间里有" + obj.data.room_users.join("、") + "，是否加入？";
                    } else {
                        obj.data.alert_text = "";
                    }
                } else {
                    appData.joinType=2;
                    if(obj.data.room_users.length >= 1){
                        obj.data.alert_text = "观战人数已满，房间里有" + obj.data.room_users.join("、") + "，是否加入游戏？";
                    } else {
                        obj.data.alert_text = "";
                    }
                }
            } else { //不能加入游戏
                if(obj.data.can_guest){
                    appData.joinType=3;
                    if(obj.data.room_users.length>=1){
                        obj.data.alert_text="游戏人数已满，是否加入观战?";
                    } else {
                        obj.data.alert_text="";
                    }
                } else {
                    appData.joinType=4;
                    obj.data.alert_text="游戏和观战人数已满";
                }
            }
            viewMethods.clickShowAlert(4,obj.data.alert_text);
        }
    },
    processJoinRoom:function(e){
        appData.player=[];
        appData.playerBoard={score:[],round:0,record:""};
        for(t=0;t<9;t++){
            appData.player.push({
                num:t+1,
                serial_num:0,
                account_id:0,
                account_status:0,
                playing_status:0,
                online_status:0,
                nickname:"",
                headimgurl:"",
                account_score:0,
                ticket_checked:0,
                is_win:!1,
                win_type:0,
                limit_time:0,
                is_operation:!1,
                win_show:!1,
                card:[],
                is_showCard:!1,
                is_pk:!1,
                is_readyPK:!1,
                card_type:0,
                messageOn:!1,
                messageText:""
            }),
            appData.playerBoard.score.push({account_id:0,nickname:"",account_score:0,isBigWinner:0});
        }

        appData.game.room=e.data.room_id;
        appData.game.currentScore=Math.ceil(e.data.benchmark);
        appData.game.score=Math.ceil(e.data.pool_score);
        appData.game.round=Math.ceil(e.data.game_num);
        appData.game.total_num=Math.ceil(e.data.total_num);
        appData.game.creator_id = Math.ceil(e.data.creator_id);
        if(2==appData.ruleInfo.chip_type){
            appData.scoreList1=[10,20,25,50];
            appData.scoreList2=[4,8,10,20];
        } else if (1==appData.ruleInfo.chip_type) {
            appData.scoreList1=[5,10,20,25];
            appData.scoreList2=[2,4,8,10];
        }else {
            appData.scoreList1=[15,25,50,100];
            appData.scoreList2=[ 6,10,20,40];
        }

        -1==e.data.limit_time&&(appData.game.time=Math.ceil(e.data.limit_time),viewMethods.timeCountDown());
        appData.player[0].serial_num=Math.ceil(e.data.serial_num);

        for(var t=0;t<9;t++)
            if(t<=9-Math.ceil(e.data.serial_num)){
                appData.player[t].serial_num=t+Math.ceil(e.data.serial_num);
            } else {
                appData.player[t].serial_num=t+Math.ceil(e.data.serial_num)-9;
            }

        appData.player[0].account_status=Math.ceil(e.data.account_status);
        appData.player[0].account_score=Math.ceil(e.data.account_score);
        appData.player[0].nickname=userData.nickname;
        appData.player[0].headimgurl=userData.headimgurl;
        appData.player[0].account_id=userData.accountId;
        appData.player[0].card=e.data.cards.concat();
        appData.player[0].card_type=e.data.card_type;
        appData.player[0].ticket_checked=e.data.ticket_checked;
        appData.game.status=Math.ceil(e.data.room_status);

        if(2==appData.game.status){
            appData.game.cardDeal=3;
            if(4==appData.player[0].account_status){
                viewMethods.cardOver(0);
            } else if(appData.ruleInfo.play_mode==2 && appData.player[0].account_status == 5){ //明牌
                viewMethods.seeMyCard();
            }
        }
        
        appData.scoreboard=e.data.scoreboard;

        //观战功能
        appData.isWatching=0;
        setTimeout(function(){
            appData.showGuest=0
        },100);
    },
    processRefreshRoom:function(e){
        appData.player=[],appData.playerBoard={score:[],round:0,record:""};
                for(t=0;t<9;t++)appData.player.push({num:t+1,serial_num:0,account_id:0,account_status:0,playing_status:0,online_status:0,nickname:"",headimgurl:"",
                    account_score:0,ticket_checked:0,is_win:!1,win_type:0,limit_time:0,is_operation:!1,win_show:!1,card:[],is_showCard:!1,is_pk:!1,is_readyPK:!1,
                    card_type:0,messageOn:!1,messageText:"我们来血拼吧"}),
                appData.playerBoard.score.push({account_id:0,nickname:"",account_score:0,isBigWinner:0});

                appData.game.currentScore=Math.ceil(e.data.benchmark),
                appData.game.score=Math.ceil(e.data.pool_score),
                2==appData.ruleInfo.chip_type?(appData.scoreList1=[10,20,25,50],appData.scoreList2=[4,8,10,20]): (1==appData.ruleInfo.chip_type ? (appData.scoreList1=[5,10,20,25],appData.scoreList2=[2,4,8,10]) : (appData.scoreList1=[15,25,50,100],appData.scoreList2=[6,10,20,40]));

                for(t=0;t<appData.player.length;t++)t<=appData.player.length-Math.ceil(e.data.serial_num)?
                    appData.player[t].serial_num=t+Math.ceil(e.data.serial_num):appData.player[t].serial_num=
                t+Math.ceil(e.data.serial_num)-appData.player.length;for(var t=0;t<appData.player.length;t++)
                for(var n=0;n<e.all_gamer_info.length;n++)
                    appData.player[t].serial_num==e.all_gamer_info[n].serial_num&&
                (appData.player[t].nickname=e.all_gamer_info[n].nickname,
                    appData.player[t].headimgurl=e.all_gamer_info[n].headimgurl,appData.player[t].account_id=e.all_gamer_info[n].account_id,
                    appData.player[t].account_score=Math.ceil(e.all_gamer_info[n].account_score),
                    appData.player[t].account_status=Math.ceil(e.all_gamer_info[n].account_status),
                    appData.player[t].online_status=Math.ceil(e.all_gamer_info[n].online_status),
                    appData.player[t].ticket_checked=e.all_gamer_info[n].ticket_checked);
                appData.player[0].card=e.data.cards.concat(),appData.player[0].card_type=e.data.card_type
            },
    processAllGamerInfo:function(e){
        for(n=0;n<9;n++)
            for(var t=0;t<e.data.length;t++)
                if(appData.player[n].serial_num==e.data[t].serial_num){
                    appData.player[n].is_guest=0;    //观战功能
                    appData.player[n].nickname=e.data[t].nickname,
                    appData.player[n].headimgurl=e.data[t].headimgurl,
                    appData.player[n].account_id=e.data[t].account_id,
                    appData.player[n].account_score=Math.ceil(e.data[t].account_score),
                    appData.player[n].account_status=Math.ceil(e.data[t].account_status),
                    appData.player[n].online_status=Math.ceil(e.data[t].online_status),
                    appData.player[n].ticket_checked=e.data[t].ticket_checked;
                }

        if(appData.player[0].account_status>2){
            setTimeout(function(){
                appData.player[0].is_showCard=!0
            },500);
        }

        if(""!=appData.scoreboard){
            for(var n=0;n<9;n++)
                for(s in appData.scoreboard)
                    if(appData.player[n].account_id==s){
                        console.log("n:"+n);
                        appData.playerBoard.score[n].num=appData.player[n].num;
                        appData.playerBoard.score[n].account_id=appData.player[n].account_id;
                        appData.playerBoard.score[n].nickname=appData.player[n].nickname;
                        appData.playerBoard.score[n].account_score=Math.ceil(appData.scoreboard[s])
                    }

            if(2==appData.game.status){
                appData.playerBoard.round=appData.game.round-1;
            } else {
                appData.playerBoard.round=appData.game.round;
            }
        }
        appData.player[0].account_status>2&&setTimeout(function(){appData.player[0].is_showCard=!0},500);
    },
    processUpdateGamerInfo:function(e){

        var has_seat = false;    //观战功能
        for(var t=0;t<9;t++)
            if(appData.player[t].serial_num==e.data.serial_num){
                appData.player[t].nickname=e.data.nickname;
                appData.player[t].headimgurl=e.data.headimgurl;
                appData.player[t].account_id=e.data.account_id;
                appData.player[t].account_score=Math.ceil(e.data.account_score);
                appData.player[t].account_status=Math.ceil(e.data.account_status);
                appData.player[t].online_status=Math.ceil(e.data.online_status);
                appData.player[t].ticket_checked=e.data.ticket_checked;
                appData.player[t].is_guest=0;    //观战功能
            } else {
                if(appData.player[t].account_id==e.data.account_id){
                    socketModule.sendRefreshRoom();
                }
                //观战功能  有位置
                if(appData.player[t].account_id == userData.accountId || 0==appData.player[t].account_id){
                    has_seat = true;
                }
            }
            //观战功能  
            appData.showSitdownButton = appData.isWatching && has_seat;
            //观战功能  加入游戏的玩家从观战者列表中剔除
            for(a=0;a<appData.guests.length;a++)
                if(appData.guests[a].account_id==e.data.account_id){
                    break;
                }
            appData.guests.splice(a,1);
    },
    processUpdateAccountStatus:function(e){
        for(var i=0;i<9;i++){
            if(appData.player[i].account_id==e.data.account_id){
                if(1==e.data.online_status){
                    appData.player[i].account_status=Math.ceil(e.data.account_status);
                    0!=i?4==appData.player[i].account_status?m4aAudioPlay("audio3"):
                    5==appData.player[i].account_status?m4aAudioPlay("audio4"):
                    6==appData.player[i].account_status&&m4aAudioPlay("audio5"):
                    appData.player[0].is_operation=!1
                } else {
                    appData.player[i].online_status=0;
                    appData.player[i].account_status=Math.ceil(e.data.account_status);

                    //观战功能   在座玩家观战中离线
                    for(a=0;a<appData.guests.length;a++)
                        if(appData.guests[a].account_id==e.data.account_id){
                            break;
                        }
                                        
                    if(0==appData.player[i].account_status){
                        //观战功能 有位置可加入
                        appData.showSitdownButton = appData.isWatching;

                        appData.player[i].account_id=0;
                        appData.player[i].playing_status=0;
                        appData.player[i].nickname="";
                        appData.player[i].headimgurl="";
                        appData.player[i].account_score=0;
                    }
                } 
            }
        }
        if(9 == i){ //观战功能  观战者离线
            for(a=0;a<appData.guests.length;a++)
                if(appData.guests[a].account_id==e.data.account_id){
                    break;
                }
            appData.guests.splice(a,1);
        }
    },
    processStartLimitTime:function(e){
        e.data.limit_time>1&&(appData.game.time=Math.ceil(e.data.limit_time),
                viewMethods.timeCountDown())
    },
    processCancelStartLimitTime:function(e){
        appData.game.time=-1
    },
    processGameStart:function(e){
        viewMethods.tableReset(0);
        appData.game.score=0;
        appData.game.time=-1;
        appData.game.is_play=!0;
        appData.game.round=appData.game.round+1;
        currentPlayerNum=-1;
        for(var t=0;t<9;t++){
            appData.player[t].is_operation=!1;
            appData.player[t].is_showCard=!1;
            for(var n=0;n<e.data.length;n++){
                if(appData.player[t].account_id==e.data[n].account_id){
                    
                    appData.player[t].ticket_checked=1;
                    appData.player[t].account_status=Math.ceil(e.data[n].account_status);
                    appData.player[t].playing_status=Math.ceil(e.data[n].playing_status);
                    appData.player[t].online_status=Math.ceil(e.data[n].online_status);
                    appData.player[t].account_score = appData.player[t].account_score - Math.ceil(appData.ruleInfo.default_score);
                    appData.player[t].limit_time=Math.ceil(e.data[n].limit_time);

                    if(appData.player[t].playing_status>1){
                        currentPlayerNum=t;
                        if(0==t){   //看牌条件
                            //appData.game.can_open = Math.ceil(e.data[n].can_open);
                            appData.game.can_look = Math.ceil(e.data[n].can_look);
                        }
                    }
                    appData.game.score = appData.game.score + Math.ceil(appData.ruleInfo.default_score);
                    viewMethods.throwCoin(0);
                }
            }
        }
        appData.game.status=2;
        viewMethods.reDeal();
        currentPlayerNum>=0&&viewMethods.playerTimeCountDown();
    },
    //明牌
    processMyCards: function(obj) { 
        if (appData.ruleInfo.play_mode==2 ) {
            if (appData.player[0].account_id == obj.data.account_id) {
                appData.player[0].card = obj.data.cards.concat();
            }
            viewMethods.seeMyCard();
        }
    },
    processNotyChooseChip:function(e){
        appData.game.is_play=!0;
        currentPlayerNum=-1;
        if(2==appData.game.status){
            for(var t=0;t<9;t++){
                appData.player[t].playing_status=1;
                if(appData.player[t].account_id==e.data.account_id){
                    appData.player[t].is_showCard=!0;
                    appData.player[t].is_operation=!1;
                    appData.player[t].playing_status=Math.ceil(e.data.playing_status);
                    appData.player[t].limit_time=Math.ceil(e.data.limit_time);
                    appData.game.can_open=e.data.can_open;
                    appData.game.can_look = e.data.can_look;  //看牌条件
                }
                if(appData.player[t].playing_status>1){
                    currentPlayerNum=t;
                }
            }
        }
        appData.pkPeople=e.data.pk_user.concat();
        if(currentPlayerNum>=0){
            viewMethods.playerTimeCountDown();
        }
    },
    processCardInfo:function(e){
        
        appData.player[0].card_type=e.data.card_type;

        if(appData.ruleInfo.play_mode == 2){    //明牌
            appData.player[0].card[2]=e.data.cards[2];
            viewMethods.mingCardOver();
        } else {
            appData.player[0].card=e.data.cards.concat();
            viewMethods.cardOver(0);
        }

        viewMethods.cardTest();
    },
    processPKCard:function(e){
                for(var t=0,n=0,a=0;a<9;a++)appData.player[a].account_id==e.data.account_id&&
                    (appData.player[a].account_score=appData.player[a].account_score-Math.ceil(e.data.score),
                        viewMethods.throwCoin(appData.player[a].num,e.data.score)),appData.player[a].account_id==e.data.loser_id&&
                (appData.player[a].account_status=7,appData.player[a].is_pk=!0,t=a),appData.player[a].account_id==e.data.winner_id&&
                (appData.player[a].is_pk=!0,n=a);appData.game.score=appData.game.score+Math.ceil(e.data.score),viewMethods.playerPK(t,n)
            },
    processBroadcastVoice:function(e){
        for(var t=0;t<9;t++)appData.player[t].account_id==e.data.account_id&&0!=t&&(m4aAudioPlay("message"+e.data.voice_num),
        viewMethods.messageSay(t,e.data.voice_num))
    },

    processUpdateAccountScore:function(e){
        for(var t=0;t<9;t++)
            if(appData.player[t].account_id==e.data.account_id){
                appData.player[t].account_score=appData.player[t].account_score-Math.ceil(e.data.score);
                if(5==appData.player[t].account_status){
                    appData.game.currentScore=Math.ceil(2.5*e.data.score);
                } else {
                    appData.game.currentScore=Math.ceil(e.data.score);
                }
                
                appData.game.score=appData.game.score+Math.ceil(e.data.score);
                if(0!=t || appData.player[0].account_id != userData.accountId){ //观战功能
                    viewMethods.throwCoin(appData.player[t].num,e.data.score);
                    m4aAudioPlay(e.data.score+"f");
                }
            }
    },
    processOpenCard:function(e){
        if(!appData.game.is_play)return 0;
        for(var t=0;t<9;t++)appData.player[t].account_id==e.data.account_id&&(appData.player[t].account_score=appData.player[t].account_score-Math.ceil(e.data.score),
            appData.game.score=appData.game.score+Math.ceil(e.data.score),
            viewMethods.throwCoin(appData.player[t].num,e.data.score))
    },
    processWin:function(e){
        appData.game.is_play=!1,appData.game.round=Math.ceil(e.data.game_num),
        appData.game.total_num=Math.ceil(e.data.total_num),appData.playerBoard.round=Math.ceil(e.data.game_num);
        for(var t=0;t<9;t++){
            if(appData.player[t].playing_status=1,0==e.data.card_type);
            else {
                for (var n = 0; n < e.data.player_cards.length; n++) {
                    appData.player[t].account_id == e.data.player_cards[n].account_id && (appData.player[t].card = e.data.player_cards[n].cards.concat());
                }
            }
            for (n in e.data.winner_score_dict) {
                appData.player[t].account_id == n && (appData.player[t].is_win = !0, appData.player[t].win_type = e.data.card_type, appData.player[t].current_win = e.data.winner_score_dict[n])
            }
            if (e.data.xipai_score_dict[appData.player[t].account_id] && e.data.card_type >= 5 && appData.ruleInfo.xipai_score > 0) {
                appData.player[t].xipai_score = e.data.xipai_score_dict[appData.player[t].account_id];
                appData.player[t].is_xipai = true;
            }
        }
        0==e.data.card_type?viewMethods.gameOver(e.data.winner_score_dict,e.data.score_board,1e3,2e3):(viewMethods.cardOver(1),e.data.total_num==e.data.game_num?
                        viewMethods.gameOver(e.data.winner_score_dict,e.data.score_board,2500,1e3):
                        viewMethods.gameOver(e.data.winner_score_dict,e.data.score_board,2500,2500)),
                e.data.total_num==e.data.game_num&&viewMethods.roundEnd()
    },
    processDiscard:function(e){appData.player[0].account_status=6},
    processLastScoreboard:function(e){
        if(void 0!=e){
        console.log(e);try{var t=new Date(1e3*parseInt(e.time)),n=t.getFullYear()+"-",a=t.getMonth()+1+"-",i=t.getDate()+" ",o=t.getHours(),r=t.getMinutes(),
        c=":";r<10&&(c+=0);var l=n+a+i+o+c+r;appData.playerBoard.round=e.game_num,appData.playerBoard.record=l,
        appData.playerBoard.score=[],void 0!=e.total_num&&null!=e.total_num&&""!=e.total_num&&(appData.game.total_num=e.total_num);var u=e.scoreboard;
        for(s in u){var p=0;userData.accountId==u[s].account_id&&(p=1),
            appData.playerBoard.score.push({account_id:u[s].account_id,nickname:u[s].name,
                account_score:Math.ceil(u[s].score),num:p})}chooseBigWinner(),
            $(".ranking .rankBack").css("opacity","1"),$(".roundEndShow").show(),$(".ranking").show(),
            canvas(),$("#endCreateRoomBtn").show()}catch(e){console.log(e)}}
    }
};
var viewMethods={
    clickShowAlert:function(e,t){console.log(e,t),
        appData.alertType=e,appData.alertText=t,appData.isShowAlert=!0,setTimeout(function(){
            var t=$(".alertText").height(),n=t;t<.15*height&&(t=.15*height),t>.8*height&&(t=.8*height);var a=t+.056*height*2+.022*height+.056*height;
            8==e&&(a=a-.022*height-.056*height);var i=t+.034*height*2,o=.022*height+(i-n)/2;$(".alert .mainPart").css("height",a+"px"),$(".alert .mainPart").css("margin-top","-"+a/2+"px"),$(".alert .mainPart .backImg .blackImg").css("height",i+"px"),$(".alert .mainPart .alertText").css("top",o+"px")},0)},
    clickCloseAlert:function(){
        22==appData.alertType?(appData.isShowAlert=!1,httpModule.getManageInfo()):appData.isShowAlert=!1
    },
    clickSitDown:function(){appData.isShowAlert=!1,socketModule.sendJoinRoom()},
    clickReady:function(){
        if(appData.player[0].is_operation||1!=appData.game.status)return 0;
        socketModule.sendReadyStart(),appData.player[0].is_operation=!0
    },
    clickCloseRoom: function() {
        socketModule.sendCloseRoom();
        appData.player[0].is_operation = true;
    },
    reDeal:function(){
        m4aAudioPlay("audio1"),appData.game.cardDeal=1,setTimeout(function(){
            appData.game.cardDeal=2,setTimeout(function(){appData.game.cardDeal=3,
                setTimeout(function(){appData.player[0].is_showCard=!0},400)},250)},250)
    },

    seeMyCard: function() {
        if(appData.player[0].account_id!=userData.accountId) return; //观战功能

        if (appData.ruleInfo.play_mode==2 ) { //明牌模式
            setTimeout(function() {
                $(".myCards .card0").addClass("card-flipped");
                $(".myCards .card1").addClass("card-flipped");
            }, 1000);
        }
    },

    mingCardOver: function() {
        if(appData.player[0].account_id!=userData.accountId) return; //观战功能

        setTimeout(function(){
            $(".myCards .card2").addClass("card-flipped");
             // $(".myCards .card2 .back").css({"z-index": "92","-webkit-transform": "rotateY(0deg)"});
             // $(".myCards .card2 .front").css({"z-index": "91","-webkit-transform": "rotateY(180deg)"});
            //$(".myCards .card2 .front").css("transform", "rotateY(0deg)");
        }, 100);
    },

    cardOver:function(e){
        if(0==e){
            $(".myCards .card0").velocity({left:0},{duration:450}),
            $(".myCards .card1").velocity({left:0},{duration:450}),
            $(".myCards .card2").velocity({left:0},{duration:450,complete:function(){
                $(".myCards .cards").addClass("card-flipped"),
                $(".myCards .card0").velocity({left:"0"},{duration:550}),
                $(".myCards .card1").velocity({left:"50%"},{duration:550}),
                $(".myCards .card2").velocity({left:"100%"},{duration:550})
            }})
        } else {
            appData.game.cardDeal=-1;
            $(".cardOver .card0").velocity({left:0},{duration:250}),
            $(".cardOver .card1").velocity({left:0},{duration:250}),
            $(".cardOver .card2").velocity({left:0},{duration:250,complete:function(){
                $(".cardOver .cards").addClass("card-flipped"),$(".cardOver .card0").velocity({left:"0"},{duration:500}),
                $(".cardOver .card1").velocity({left:"25%"},{duration:500}),
                $(".cardOver .card2").velocity({left:"50%"},{duration:500})
            }});
            
            if(5==appData.player[0].account_status){
                appData.player[0].account_status=4;
                viewMethods.cardOver(0);
            } else if (appData.player[0].account_status == 4 && appData.player[0].account_id!=userData.accountId){ //观战功能
                //$(".myCards .isSeen1").css("display","none");
                viewMethods.cardOver(0);
            }
        }
    },
    cardTest:function(){
        4==appData.player[0].account_status&&0==appData.player[0].card.length&&socketModule.sendRefreshRoom()
    },
    gameOver:function(e,t,n,a){
        for(var i=0;i<9;i++)for(s in t)appData.player[i].account_id==s&&(appData.player[i].account_score=Math.ceil(t[s]),
            appData.playerBoard.score[i].num=appData.player[i].num,appData.playerBoard.score[i].account_id=appData.player[i].account_id,
            appData.playerBoard.score[i].nickname=appData.player[i].nickname,appData.playerBoard.score[i].account_score=appData.player[i].account_score);
            setTimeout(function(){for(var e=0,n=0;n<appData.player.length;n++)appData.player[n].is_win&&
                (appData.player[n].win_show=!0,0==n&&mp3AudioPlay("win"),0==e&&(e=1,numD=appData.player[n].num,
                    setTimeout(function(){
                        viewMethods.selectCoin(numD,t)},1500)));
                var i=new Date,o="";o+=i.getFullYear()+"-",o+=i.getMonth()+1+"-",o+=i.getDate()+"  ",o+=i.getHours()+":",
                i.getMinutes()>=10?o+=i.getMinutes():o+="0"+i.getMinutes(),appData.playerBoard.record=o,
                setTimeout(function(){viewMethods.tableReset(1)},a)},n)},
    showMessage:function(){
        if(appData.player[0].account_id!=userData.accountId) return; //观战功能

        appData.isShowMessage=!0;
        disable_scroll();
        setTimeout(function(){
            if(appData.bScroll){
                appData.bScroll.refresh();
            } else {
                appData.bScroll=new BScroll(document.getElementById("message-box"),{
                    startX:0,
                    startY:0,
                    scrollY:!0,
                    scrollX:!1,
                    click:!0
                });
            }
        }, 10);
    },
    hideMessage:function(){
        appData.isShowMessage=!1;
        enable_scroll();
    },
    messageOn:function(e){socketModule.sendBroadcastVoice(e),
        m4aAudioPlay("message"+e),
        viewMethods.messageSay(0,e),
        viewMethods.hideMessage()},
    messageSay:function(e,t){appData.player[e].messageOn=!0,appData.player[e].messageText=appData.message[t].text,
        setTimeout(function(){appData.player[e].messageOn=!1},2500)},
    closeEnd:function(){$(".ranking .rankBack").css("opacity","0.7"),$(".end").hide(),
    $(".roundEndShow").hide(),$(".ranking").hide(),window.location.reload()},
    roundEnd:function(){for(var e=0;e<appData.player.length;e++)0==appData.player[e].online_status&&(appData.player[e].account_id=0,appData.player[e].playing_status=0,
        appData.player[e].online_status=0,appData.player[e].nickname="",appData.player[e].headimgurl="",appData.player[e].account_score=0),
    appData.player[e].ticket_checked=0;chooseBigWinner(),$(".ranking .rankBack").css("opacity","1"),$(".roundEndShow").show(),
    setTimeout(function(){$(".ranking").show(),canvas()},3500)},timeCountDown:function(){
        if(1!=isTimeLimitShow)
            return appData.game.time<=0?(isTimeLimitShow=!1,0):(isTimeLimitShow=!0,appData.game.time--,
                void(timeLimit=setTimeout(function(){isTimeLimitShow=!1,viewMethods.timeCountDown()},1e3)))},
    playerTimeCountDown:function(){
        if(1!=isPlayerTimeLimitShow)return appData.player[currentPlayerNum].limit_time<=0||
            currentPlayerNum<0?(isPlayerTimeLimitShow=!1,0):(isPlayerTimeLimitShow=!0,appData.player[currentPlayerNum].limit_time--,
                void setTimeout(function(){isPlayerTimeLimitShow=!1,viewMethods.playerTimeCountDown()},1e3))},
    tableReset:function(e){
        for(var t=0;t<9;t++){
            if(appData.player[t].account_status>1&&1==e){
                appData.player[t].account_status=1;
            }
            appData.player[t].playing_status=0;
            appData.player[t].is_win=!1;
            appData.player[t].is_operation=!1;
            appData.player[t].win_type=0;
            appData.player[t].win_show=!1;
            appData.player[t].card=[];
            appData.player[t].card_type=0;
            appData.player[t].is_showCard=!1;
            appData.player[t].is_readyPK=!1;
            appData.player[t].is_pk=!1;
            appData.player[t].is_xipai = false;
        }

        appData.game.can_open=0;
        appData.game.can_look=1;    //看牌条件
        appData.game.score=0;
        appData.game.cardDeal=0;
        appData.game.currentScore=0;
        appData.game.status=1;
        $(".cards").removeClass("card-flipped");
        $(".scoresArea").empty();
    },
    throwCoin:function(e,t){
        if(0==e){
            $(".scoresArea").append("<div class='coin coinType"+ruleInfo.default_score+"' style='top:"+(140*per-28)*Math.random()+"px;left:"+(140*per-28)*Math.random()+"px;' ></div>");
            return 0;
        }
        
        $(".scoresArea").append("<div class='coin coin"+e+" coinType"+t+"' ></div>");
        $(".coin"+e).velocity(
            {top:(140*per-28)*Math.random(),left:(140*per-28)*Math.random()},
            {duration:300,complete:function(){$(".coin").removeClass("coin"+e)}}
        );
    },

    selectCoin:function(e,t){
        var n=0,a=0;

        switch(e){
            case 1:
                n="36vh",a=40;
                break;
            case 2:
                n="23vh",a=150;
                break;
            case 3:
                n="10vh",a=150;
                break;
            case 4:
                n="-4vh",a=150;
                break;
            case 5:
                n="-16vh",a=110;
                break;
            case 6:
                n="-16vh",a=-40;
                break;
            case 7:
                n="-4vh",a=-60;
                break;
            case 8:
                n="10vh",a=-60;
                break;
            case 9:
                n="23vh",a=-60;
                break;
            default:
                break;
        }

        $(".coin").velocity(
            {top:n,left:a},
            {duration:600,complete:function(){$(".scoresArea").empty()}}
        );
    },

    playerPK:function(e,t){
            $(".pk1").css("left","-60%");
            $(".pk2").css("right","-60%");
            $(".playerPK .quitBack").hide();
            $(".playerPK .background").attr("src",globalData.fileUrl+"files/images/flower/comB.png");

            appData.turn=0==e?t<5?0:1:t<e?0:1;

            if(0==appData.turn){
                appData.pk1.nickname=appData.player[e].nickname;
                appData.pk1.headimgurl=appData.player[e].headimgurl;
                appData.pk1.account_score=appData.player[e].account_score;
                appData.pk1.account_status=appData.player[e].account_status;
                appData.pk2.nickname=appData.player[t].nickname;
                appData.pk2.headimgurl=appData.player[t].headimgurl;
                appData.pk2.account_score=appData.player[t].account_score;
                appData.pk2.account_status=appData.player[t].account_status;
            } else {
                appData.pk1.nickname=appData.player[t].nickname;
                appData.pk1.headimgurl=appData.player[t].headimgurl;
                appData.pk1.account_score=appData.player[t].account_score;
                appData.pk1.account_status=appData.player[t].account_status;
                appData.pk2.nickname=appData.player[e].nickname;
                appData.pk2.headimgurl=appData.player[e].headimgurl;
                appData.pk2.account_score=appData.player[e].account_score;
                appData.pk2.account_status=appData.player[e].account_status;
            }
           
            appData.pk.round=2;
            setTimeout(function(){
                    m4aAudioPlay("com");
                    $(".pk1").velocity({left:0},{duration:500});
                    $(".pk2").velocity({right:0},{
                        duration:500,
                        complete:function(){
                            appData.pk.round=3;
                            setTimeout(function(){
                                appData.pk.round=4;
                                if(7==appData.pk1.account_status){
                                    $(".pk1 .quitBack").fadeIn();
                                    $(".pk1 .background").attr("src",globalData.fileUrl+"files/images/common/player_bg.png");
                                } else {
                                    $(".pk1 .background").attr("src",globalData.fileUrl+"files/images/common/player_selected.png");
                                }
                            
                                if(7==appData.pk2.account_status){
                                    $(".pk2 .quitBack").fadeIn();
                                    $(".pk2 .background").attr("src",globalData.fileUrl+"files/images/common/player_bg.png");
                                } else {
                                    $(".pk2 .background").attr("src",globalData.fileUrl+"files/images/common/player_selected.png");
                                }
                            
                                setTimeout(function(){
                                    appData.pk.round=0;
                                    for(var e=0;e<appData.player.length;e++)
                                        appData.player[e].is_pk=!1
                                },2e3);
                            },800);
                        }
                    });
            },0);
    },
    choose:function(e,t){
        if(appData.player[0].is_operation)return 0;
        if(1==e) {
            socketModule.sendClickToLook(),
                m4aAudioPlay("audio3");
        }else if(2==e) {
            socketModule.sendChooseChip(t), m4aAudioPlay(t + "f"),
                viewMethods.throwCoin(1, t), appData.player[0].is_operation = !0;
        }else if(3==e) {
            socketModule.sendDiscard(),
                m4aAudioPlay("audio5"), appData.player[0].is_operation = !0;
        }else if(4==e){
            for(var n=0,a=0;a<appData.player.length;a++){
                4!=appData.player[a].account_status&&5!=appData.player[a].account_status||n++;
            }
            if(2==n) {
                socketModule.sendOpenCard(),
                    m4aAudioPlay("audio2"), appData.player[0].is_operation = !0;
            }else{
                for(a=0;a<appData.player.length;a++){
                    appData.player[a].is_readyPK=!1;
                    for(var i=0;i<appData.pkPeople.length;i++) {
                        appData.player[a].account_id == appData.pkPeople[i] && (appData.player[a].is_readyPK = !0)
                    }
                }
                appData.pk.round=1}
        }else{
            5==e&&(socketModule.sendPkCard(t),appData.player[0].is_operation=!0)
        }
    },
    quitPk:function(){appData.pk.round=0}
};

var width=window.innerWidth;
var height=window.innerHeight;
var numD=0;
var isTimeLimitShow=!1;
var isPlayerTimeLimitShow=!1;
var currentPlayerNum=0;

var ruleInfo={
    type:0,
    isShow:!1,
    isShowRule:!1,
    chip_type:1,
    ticket_count:1,
    disable_pk:0,
    disable_look:0,
    upper_limit:0,
    default_score: 4,
    pk_score: 0,
    look_score: 0,
    play_mode: 1,
    rule_height:60,
    xipai_score:0,
};
var editAudioInfo={isShow:!1,backMusic:1,messageMusic:1};
var audioInfo={backMusic:1,messageMusic:1};
localStorage.backMusic?(editAudioInfo.backMusic=localStorage.backMusic,audioInfo.backMusic=localStorage.backMusic):localStorage.backMusic=1;
localStorage.messageMusic?(editAudioInfo.messageMusic=localStorage.messageMusic,audioInfo.messageMusic=localStorage.messageMusic):localStorage.messageMusic=1;

appData={
    //观战功能
    isWatching:0,
    guests:[],
    showGuest:0,
    showSitdownButton:0,
    showWatchButton:1,
    joinType:0,

    roomStatus:globalData.roomStatus,
    isAA:!1,isAutoActive:!1,isShop:globalData.isShop,
    scoreList1:[5,10,20,25],
    scoreList2:[2,4,8,10],
    width:window.innerWidth,
    height:window.innerHeight,
    roomCard:Math.ceil(globalData.card),
    is_connect:!1,player:[],
    scoreboard:"",activity:[],
    isShowAlert:!1,
    isShowMessage:!1,
    alertType:0,
    alertText:"",
    base_score:0,
    playerBoard:{score:[],round:0,record:""},
    game:game,
    wsocket:ws,
    connectOrNot:!0,
    socketStatus:0,
    heartbeat:null,
    select:1,
    ticket_count:0,
    isDealing:!1,
    message:message,
    pkPeople:[],
    turn:0,
    pk:{turn:0,round:0},
    pk1:{nickname:"",headimgurl:"",account_score:0,account_status:0},
    pk2:{nickname:"",headimgurl:"",account_score:0,account_status:0},
    isShowRecord:!1,recordList:[],
    ruleInfo:ruleInfo,
    editAudioInfo:editAudioInfo,
    audioInfo:audioInfo,
    isReconnect:!0,
    bScroll:null,
    isShowNoty:!1,
    notyMsg:"",
    isShowNoteImg:!1
};


var resetState = function resetState() {
    appData.player = [];
    appData.playerBoard = {
        "score": [],
        "round": 0,
        "record": "",
    };

    for (var i = 0; i < 9; i++) {
        appData.player.push({
            "num": i + 1,
            "serial_num": i + 1,
            "account_id": 0,
            "account_status": 0,
            "playing_status": 0,
            "online_status": 0,
            "nickname": "",
            "headimgurl": "",
            "account_score": 0,
            "ticket_checked": 0,
            "is_win": false,
            "win_type": 0,
            "limit_time": 0,
            "current_win": 0,
            "is_operation": false,
            "win_show": false,
            "card": [],
            "is_showCard": false,
            "is_pk": false,
            "is_readyPK": false,
            "card_type": 0,
            "messageOn": false,
            "messageText": "",
            "is_xipai": false,
            "xipai_score": 0,
        });

        appData.playerBoard.score.push({
            "account_id": 0,
            "nickname": "",
            "account_score": 0,
            "isBigWinner": 0,
        });
    }

    if (appData.isAuthPhone != 1) {
        httpModule.getManageInfo();
    }
    // httpModule.getRoomCardInfo();
    //广播 
    setTimeout(function () {
        if (globalData.isNotyMsg != undefined && globalData.isNotyMsg != null) {
            appData.notyMsg = globalData.notyMsg;
            if (globalData.isNotyMsg == 1) {
                appData.isShowNoty = true;
                setTimeout(function () {
                    appData.isShowNoty = false;
                }, globalData.notyTime * 1000);
            }
        } else {
            globalData.isNotyMsg = 0;
        }
        $('#marquee').marquee({
            //speed in milliseconds of the marquee
            duration: globalData.notySpeed,
            //gap in pixels between the tickers
            gap: 400,
            //time in milliseconds before the marquee will start animating
            delayBeforeStart: 0,
            //'left' or 'right'
            direction: 'left',
            //true or false - should the marquee be duplicated to show an effect of continues flow
            duplicated: true
        });
    
    }, 50);
    //end 广播
};
var connectSocket=function(e,t,n,a,i){(ws=new WebSocket(e)).onopen=t,ws.onmessage=n,ws.onclose=a,ws.onerror=i};
var wsOpenCallback=function(e){
    logMessage("websocket is opened");
    appData.connectOrNot=!0;
    appData.heartbeat&&clearInterval(appData.heartbeat);
    appData.heartbeat=setInterval(function(){
        appData.socketStatus=appData.socketStatus+1;
        appData.socketStatus>2&&(appData.connectOrNot=!1);
        appData.socketStatus>3&&appData.isReconnect&&window.location.reload();
        ws.readyState==WebSocket.OPEN&&ws.send("@")
    },3e3);
    socketModule.sendPrepareJoinRoom();
};
var wsMessageCallback=function wsMessageCallback(evt){
    appData.connectOrNot=!0;
    if("@"==evt.data){
        appData.socketStatus=0;
        return 0;
    }
    var obj=eval("("+evt.data+")");
    if(-201==obj.result){
        viewMethods.clickShowAlert(31,obj.result_message);
    } else if(-202==obj.result){
        appData.isReconnect=!1;
        socketModule.closeSocket();
        viewMethods.clickShowAlert(32,obj.result_message);
    } else if(-203==obj.result){
        methods.reloadView();
    }
    if(0!=obj.result){
        if(obj.operation==wsOperation.JoinRoom){
            if(1==obj.result){
                if(1==obj.data.alert_type){
                    viewMethods.clickShowAlert(1,obj.result_message);
                }else if(2==obj.data.alert_type){
                    viewMethods.clickShowAlert(2,obj.result_message);
                }else if(3==obj.data.alert_type){
                    viewMethods.clickShowAlert(11,obj.result_message);
                } else {
                    viewMethods.clickShowAlert(7,obj.result_message);
                }
            } else {
                 obj.result,viewMethods.clickShowAlert(7,obj.result_message);
            }
        } else if(obj.operation==wsOperation.ReadyStart){
            if(1==obj.result){
                viewMethods.clickShowAlert(1,obj.result_message);
            } 
        } else if(obj.operation==wsOperation.PrepareJoinRoom){
            if(obj.result>0){
                socketModule.processGameRule(obj);
            }
            if(1==obj.result){
                if(1==obj.data.alert_type){
                    viewMethods.clickShowAlert(1,obj.result_message);
                } else if(2==obj.data.alert_type){
                    viewMethods.clickShowAlert(2,obj.result_message);
                } else if(3==obj.data.alert_type){
                    viewMethods.clickShowAlert(11,obj.result_message);
                }
            } else {
                viewMethods.clickShowAlert(7,obj.result_message);
            }
        } else if(obj.operation==wsOperation.RefreshRoom){
            window.location.reload();
        }
        appData.player[0].is_operation=!1;
    } else {
        obj.operation==wsOperation.PrepareJoinRoom?socketModule.processPrepareJoinRoom(obj):
        obj.operation==wsOperation.JoinRoom?socketModule.processJoinRoom(obj):
        obj.operation==wsOperation.ActiveRoom?socketModule.processActiveRoom(obj):
        obj.operation==wsOperation.RefreshRoom?socketModule.processRefreshRoom(obj):
        obj.operation==wsOperation.AllGamerInfo?socketModule.processAllGamerInfo(obj):
        obj.operation==wsOperation.UpdateGamerInfo?socketModule.processUpdateGamerInfo(obj):
        obj.operation==wsOperation.UpdateAccountStatus?socketModule.processUpdateAccountStatus(obj):
        obj.operation==wsOperation.UpdateAccountShow?socketModule.processUpdateAccountShow(obj):
        obj.operation==wsOperation.UpdateAccountMultiples?socketModule.processUpdateAccountMultiples(obj):
        obj.operation==wsOperation.StartLimitTime?socketModule.processStartLimitTime(obj):
        obj.operation==wsOperation.CancelStartLimitTime?socketModule.processCancelStartLimitTime(obj):
        obj.operation==wsOperation.GameStart?socketModule.processGameStart(obj):
        obj.operation==wsOperation.NotyChooseChip?socketModule.processNotyChooseChip(obj):
        obj.operation==wsOperation.UpdateAccountScore?socketModule.processUpdateAccountScore(obj):
        obj.operation==wsOperation.OpenCard?socketModule.processOpenCard(obj):
        obj.operation==wsOperation.Win?socketModule.processWin(obj):
        obj.operation==wsOperation.Discard?socketModule.processDiscard(obj):
        obj.operation==wsOperation.BroadcastVoice?socketModule.processBroadcastVoice(obj):
        obj.operation==wsOperation.StartBet?socketModule.processStartBet(obj):
        obj.operation==wsOperation.StartShow?socketModule.processStartShow(obj):
        obj.operation==wsOperation.PkCard?socketModule.processPKCard(obj):
        obj.operation==wsOperation.CardInfo?socketModule.processCardInfo(obj):
        //明牌
        obj.operation==wsOperation.MyCards?socketModule.processMyCards(obj):
        //观战功能
        obj.operation==wsOperation.GuestRoom?socketModule.processGuestRoom(obj):
        obj.operation==wsOperation.AllGuestInfo?socketModule.processAllGuestInfo(obj):
        obj.operation==wsOperation.UpdateGuestInfo?socketModule.processUpdateGuestInfo(obj):

        logMessage(obj.operation);
    }
};

var wsCloseCallback=function(e){
    logMessage("websocket closed：");
    logMessage(e);
    appData.connectOrNot=!1;
    reconnectSocket()
};
var wsErrorCallback=function(e){
    logMessage("websocket onerror：");
    logMessage(e);
    appData.connectOrNot=!1
};
var reconnectSocket=function(){
    if(appData.isReconnect&&4!=globalData.roomStatus){
        if(ws){
            logMessage(ws.readyState);
            if(1==ws.readyState)
                return;
            ws=null;
        }
        logMessage("reconnectSocket");
        connectSocket(globalData.socket,wsOpenCallback,wsMessageCallback,wsCloseCallback,wsErrorCallback);
    }
};
var m4aAudioPlay=function(e){
    if(!audioModule.audioOn)
        return 0;
    audioModule.playSound(e);
};
var mp3AudioPlay=function(e){
    if(!audioModule.audioOn)
        return 0;
    audioModule.playSound(e)
};

var audioModule={
        audioOn:!1,
        audioContext:null,
        audioBuffers:[],
        baseUrl:"",
        initModule:function(e){
            this.baseUrl=e;
            this.audioBuffers=[];
            window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext||window.msAudioContext;
            this.audioContext=new window.AudioContext
        },
        stopSound:function(e){
            var t=this.audioBuffers[e];
            t&&t.source&&(t.source.stop(0),t.source=null);
        },
        playSound:function(e,t){
            if("backMusic"==e){
                if(0==audioInfo.backMusic)
                    return;
                }else if(0==audioInfo.messageMusic)
                return;
            var n=this.audioBuffers[e];
            if(n)try{
                if(void 0!=WeixinJSBridge){
                    WeixinJSBridge.invoke("getNetworkType",{},function(e){
                        n.source=null;
                        n.source=audioModule.audioContext.createBufferSource();
                        n.source.buffer=n.buffer;
                        n.source.loop=!1;
                        var a=audioModule.audioContext.createGain();
                        1==t?(n.source.loop=!0,a.gain.value=.7):a.gain.value=1;
                        n.source.connect(a);
                        a.connect(audioModule.audioContext.destination);
                        n.source.start(0);
                    });
                }
            }catch(e){
                logMessage(e);
                n.source.start(0);
            }
        },
        initSound:function(e,t){
            this.audioContext.decodeAudioData(e,function(e){
                audioModule.audioBuffers[t]={name:t,buffer:e,source:null};
                "backMusic"==t&&(audioModule.audioOn=!0,audioModule.playSound(t,!0));
            },function(e){
                logMessage("Error decoding file",e);
            });
        },
        loadAudioFile:function(e,t){
            var n=new XMLHttpRequest;
            n.open("GET",e,!0);
            n.responseType="arraybuffer";
            n.onload=function(e){
                audioModule.initSound(n.response,t)
            };
            n.send();
        },
        loadAllAudioFile:function(){
            if (globalData.roomStatus == 4) {
                return;
            }
    
            if (isLoadAudioFile == true) {
                return;
            }
    
            isLoadAudioFile = true;
    
            this.loadAudioFile(this.baseUrl + 'files/audio/flower/back2.mp3', "backMusic");
    
            var audioUrl = ["5f.m4a", "50f.m4a", "2f.m4a", "4f.m4a", "8f.m4a", "25f.m4a", "10f.m4a", "20f.m4a", "audio1.m4a", "audio2.m4a", "audio3.m4a", "audio4.m4a", "audio5.m4a", "com.m4a", "lose.mp3", "win.mp3"];
            var audioName = ["5f", "50f", "2f", "4f", "8f", "25f", "10f", "20f", "audio1", "audio2", "audio3", "audio4", "audio5", "com", "lose", "win"];
            for (var i = 0; i < audioUrl.length; i++) {
                this.loadAudioFile(this.baseUrl + 'files/d_2/audio/' + audioUrl[i], audioName[i]);
            }
    
            var audioMessageUrl = ["message9.m4a", "message10.m4a", "message11.m4a", "message1.m4a", "message2.m4a", "message3.m4a", "message4.m4a", "message5.m4a", "message6.m4a", "message7.m4a", "message8.m4a"];
            var audioMessageName = ["message0", "message1", "message2", "message3", "message4", "message5", "message6", "message7", "message8", "message9", "message10"];
            for (var i = 0; i < audioMessageUrl.length; i++) {
                this.loadAudioFile(this.baseUrl + 'files/d_2/audio/' + audioMessageUrl[i], audioMessageName[i]);
            }
        }
};
audioModule.initModule(globalData.fileUrl);

var initView=function(){
    $("#app-main").width(appData.width);
    $("#app-main").height(appData.height);
    $("#table").width(appData.width);
    $("#table").height(appData.height);
    $(".ranking").css("width",2*appData.width);
    $(".ranking").css("height",2*appData.width*1.621);
    window.onload=function(){
        var e=["table","vinvite","valert","vmessage","vshop","vcreateRoom","vroomRule","endCreateRoom","endCreateRoomBtn"];
        t=e.length;
        for(n=0;n<t;n++){
            var a=document.getElementById(e[n]);
            a&&a.addEventListener("touchmove",function(e){
                e.preventDefault()
            },!1);
        }
    };
};
var methods={
    showAlert:viewMethods.clickShowAlert,
    showMessage:viewMethods.showMessage,
    closeAlert:viewMethods.clickCloseAlert,
    sitDown:viewMethods.clickSitDown,
    seeMyCard4:viewMethods.seeMyCard4,
    seeMyCard5:viewMethods.seeMyCard5,
    imReady:viewMethods.clickReady,
    imCloseRoom: viewMethods.clickCloseRoom,
    robBanker:viewMethods.clickRobBanker,
    showCard:viewMethods.clickShowCard,
    selectTimesCoin:viewMethods.clickSelectTimesCoin,
    hideMessage:viewMethods.hideMessage,
    closeEnd:viewMethods.closeEnd,
    messageOn:viewMethods.messageOn,
    quitPk:viewMethods.quitPk,
    choose:viewMethods.choose,
    home:function(){
       window.location.href = globalData.baseUrl + "f/ym";
    },
    showGameRule:function(){
        4!=appData.roomStatus&&(appData.ruleInfo.isShowRule=!0);
    },
    cancelGameRule:function(){appData.ruleInfo.isShowRule=!1},
    showAudioSetting:function(){
        appData.editAudioInfo.backMusic=appData.audioInfo.backMusic;
        appData.editAudioInfo.messageMusic=appData.audioInfo.messageMusic;
        appData.editAudioInfo.isShow=!0;
    },
    cancelAudioSetting:function(){appData.editAudioInfo.isShow=!1},
    confirmAudioSetting:function(){
        appData.editAudioInfo.isShow=!1,appData.audioInfo.backMusic=appData.editAudioInfo.backMusic;
        appData.audioInfo.messageMusic=appData.editAudioInfo.messageMusic;
        localStorage.backMusic=appData.editAudioInfo.backMusic;
        localStorage.messageMusic=appData.editAudioInfo.messageMusic;
        if(1==appData.audioInfo.backMusic){
            audioModule.stopSound("backMusic");
            audioModule.playSound("backMusic",!0);
        } else {
            audioModule.stopSound("backMusic");
        }
    },
    setBackMusic:function(){0==appData.editAudioInfo.backMusic?appData.editAudioInfo.backMusic=1:appData.editAudioInfo.backMusic=0},
    setMessageMusic:function(){0==appData.editAudioInfo.messageMusic?appData.editAudioInfo.messageMusic=1:appData.editAudioInfo.messageMusic=0},
    
    reloadView:function(){window.location.reload();},
    showNoteImg:function(){appData.isShowNoteImg=!0},
    hideNoteImg:function(){appData.isShowNoteImg=!1},

    //观战功能
    guestRoom:function(){
        socketModule.sendGuestRoom()
    },
    hideGuests:function(){
        appData.showGuest=0
    },
    showGuests:function(){
        appData.showSitdownButton=0;
        appData.showWatchButton=!appData.isWatching && appData.player[0].account_status<2;

        if(appData.isWatching){
            for(var e=0;e<appData.player.length;e++)
                if(appData.player[e].account_id==userData.accountId || 0==appData.player[e].account_id){
                    appData.showSitdownButton = 1;
                    break
                }
        }
        appData.showGuest=1;
    }
};

var vueLife={
    vmCreated:function(){
        logMessage("vmCreated");
        resetState();
        initView();
        4!=globalData.roomStatus&&$("#loading").hide();
        $(".main").show();
    },
    vmUpdated:function(){logMessage("vmUpdated")},
    vmMounted:function(){
        logMessage("vmMounted");
        $("#marquee").css("opacity",0);
        setTimeout(function(){
            $("#marquee").css("opacity",1);
            $("#marquee").marquee({
                duration:globalData.notySpeed,
                gap:50,
                delayBeforeStart:0,
                direction:"left",
                duplicated:!0
            });
        },100);
    },
    vmDestroyed:function(){logMessage("vmDestroyed")}
};

var vm=new Vue({
    el:"#app-main",
    data:appData,
    methods:methods,
    created:vueLife.vmCreated,
    updated:vueLife.vmUpdated,
    mounted:vueLife.vmMounted,
    destroyed:vueLife.vmDestroyed
});

function preventDefaultFn(event) {
    event.preventDefault();
}
function disable_scroll() {
    $('body').on('touchmove', preventDefaultFn);
}
function enable_scroll() {
    $('body').off('touchmove', preventDefaultFn);
}


$(function(){
    $(".place").css("width",140*per);
    $(".place").css("height",140*per);
    $(".place").css("top",270*per);
    $(".place").css("left",195*per);
    $(".showRanking").click(function(){
        $(".Ranking").show();
    });
    $(".hideRanking").click(function(){
        $(".Ranking").hide();
    });
    sessionStorage.isPaused="false";
    var e,t;
    if(void 0!==document.hidden){
        e="hidden";
        t="visibilitychange";
    } else if(void 0!==document.webkitHidden){
        e="webkitHidden";
        t="webkitvisibilitychange";
    }
    if(void 0===document.addEventListener||void 0===e){
        alert("This demo requires a browser such as Google Chrome that supports the Page Visibility API.");
    } else {
        document.addEventListener(t,function(){
            if(document[e]){
                audioModule.audioOn=!1;
                audioModule.stopSound("backMusic");
            } else if("true"!==sessionStorage.isPaused){
                audioModule.audioOn=!0;
                audioModule.stopSound("backMusic");
                audioModule.playSound("backMusic",!0);
            }
        },!1);
    }
 });
   
var wsctop=0;
var shareContent="";
function getShareContent() {
    shareContent = "\n";

    if (appData.ruleInfo.play_mode == 2) {
        shareContent = shareContent + '模式：明牌 ';
    }

    shareContent = shareContent + ' 底分：' + appData.ruleInfo.default_score + '分';
    if (appData.ruleInfo.chip_type == 1) {
        shareContent = shareContent + '筹码：2/5，4/10，8/20，10/25';
    } else if (appData.ruleInfo.chip_type == 2) {
        shareContent = shareContent + '筹码：4/10，8/20，10/25，20/50';
    } else {
        shareContent = shareContent + '筹码：6/15，10/25，20/50，40/100';
    }


    if (appData.ruleInfo.disable_look == 1 || appData.ruleInfo.disable_pk == 1) {
        shareContent = shareContent + ' 规则：';
        if (appData.ruleInfo.disable_look == 1) {
            shareContent = shareContent + '首轮不能看牌';
        }

        if (appData.ruleInfo.disable_pk == 1) {
            shareContent = shareContent + '闷牌，全场禁止比牌';
        }
    }

    if (appData.ruleInfo.ticket_count == 2) {
        shareContent = shareContent + ' 局数：12局x6张房卡';
    } else {
        shareContent = shareContent + ' 局数：24局x12张房卡';
    }
    if (appData.ruleInfo.upper_limit == 0) {
        shareContent = shareContent + ' 上限：无';
    } else {
        shareContent = shareContent + ' 上限：' + appData.ruleInfo.upper_limit;
    }
    shareContent = shareContent + '  比牌：>=' + appData.ruleInfo.pk_score + '分';
    shareContent = shareContent + '  看牌：>=' + appData.ruleInfo.look_score + '分';
};

function canvas() {
    var target = document.getElementById("ranking");
    html2canvas(target, {
        allowTaint: true,
        taintTest: false,
        onrendered: function(canvas) {
            canvas.id = "mycanvas";
            var dataUrl = canvas.toDataURL('image/jpeg', 0.3);
            $("#end").attr("src", dataUrl);
            $(".end").show();
            $('.ranking').hide();
            //newGame();
        }
    });
};

function chooseBigWinner() {
    var length = appData.playerBoard.score.length;
    var maxScore = 1;
    for (var i = 0; i < length; i++) {
        appData.playerBoard.score.isBigWinner = 0;
        if (appData.playerBoard.score[i].account_score > maxScore) {
            maxScore = appData.playerBoard.score[i].account_score;
        }
    }

    for (var j = 0; j < length; j++) {
        if (appData.playerBoard.score[j].account_score == maxScore) {
            appData.playerBoard.score[j].isBigWinner = 1;
        }
    }

    //对积分榜排序
    appData.playerBoard.score.sort(function(a,b){
        return b.account_score - a.account_score;
    });
};

function logMessage(message) {
    console.log(message);
};


if(4==globalData.roomStatus){
    setTimeout(function(){
        try{
            var obj=eval("("+globalData.scoreboard+")");
            setTimeout(function(){
                socketModule.processLastScoreboard(obj)
            },0);
        } catch(e){
            console.log(e);
            setTimeout(function(){
                socketModule.processLastScoreboard("");
            },0);
        }
    },50);
}

var wxModule={
    config:function(){
        wx.config({
            debug:!1,
            appId:configData.appId,
            timestamp:configData.timestamp,
            nonceStr:configData.nonceStr,
            signature:configData.signature,
            jsApiList:["onMenuShareTimeline","onMenuShareAppMessage","hideMenuItems"]
        });
        getShareContent();
        wx.onMenuShareTimeline({
            title:"天天娱乐9人炸金花(房间号:"+globalData.roomNumber+")",
            desc:shareContent,
            link:globalData.roomUrl,
            imgUrl:globalData.fileUrl+"files/images/flower/share_icon.jpg",
            success:function(){},
            cancel:function(){}
        });
        wx.onMenuShareAppMessage({
            title:"天天娱乐9人炸金花(房间号:"+globalData.roomNumber+")",
            desc:shareContent,
            link:globalData.roomUrl,
            imgUrl:globalData.fileUrl+"files/images/flower/share_icon.jpg",
            success:function(){},
            cancel:function(){}
        });
    }
};
wx.config({
    debug:!1,
    appId:configData.appId,
    timestamp:configData.timestamp,
    nonceStr:configData.nonceStr,
    signature:configData.signature,
    jsApiList:["onMenuShareTimeline","onMenuShareAppMessage","hideMenuItems"]
});
var isLoadAudioFile=!1;
wx.ready(function(){
    audioModule.loadAllAudioFile();
    wx.hideMenuItems({
        menuList:["menuItem:copyUrl","menuItem:share:qq","menuItem:share:weiboApp","menuItem:favorite","menuItem:share:facebook","menuItem:share:QZone","menuItem:refresh"]
    });
    getShareContent();
    wx.onMenuShareTimeline({
        title:"天天娱乐9人炸金花(房号:"+globalData.roomNumber+")",
        desc:shareContent,link:globalData.roomUrl,
        imgUrl:globalData.fileUrl+"files/images/flower/share_icon.jpg",
        success:function(){},
        cancel:function(){}
    });
    wx.onMenuShareAppMessage({
        title:"天天娱乐9人炸金花(房号:"+globalData.roomNumber+")",
        desc:shareContent,
        link:globalData.roomUrl,
        imgUrl:globalData.fileUrl+"files/images/flower/share_icon.jpg",
        success:function(){},
        cancel:function(){}
    });
});
wx.error(function(e){});